import datetime, time
import json
import os
import zipfile
from warnings import catch_warnings
from jsonpath import jsonpath
import pandas as pd

DAY_FORMAT = '%Y-%m-%d'
DIFF_VAR = 0.01


class Objects(object):
    @staticmethod
    def valueOf():
        pass

    @staticmethod
    def isBreakDown(pctChg, flag):
        pass

    @staticmethod
    def isLimitDown(code, pctChg):
        if code.startswith("sh.60") or code.startswith("sz.00"):
            return abs(10 + pctChg) < DIFF_VAR
        if code.startswith("sh.68") or code.startswith("sz.30"):
            return abs(20 + pctChg) < DIFF_VAR
        return False

    @staticmethod
    def isLimitUp(code, pctChg):
        if code.startswith("sh.60") or code.startswith("sz.00"):
            return abs(pctChg - 10) < DIFF_VAR
        if code.startswith("sh.68") or code.startswith("sz.30"):
            return abs(pctChg - 20) < DIFF_VAR
        return False

    @staticmethod
    def isLimit(code, preClose, close, isUp):
        if code.startswith("sh.60") or code.startswith("sz.00"):
            if isUp:
                return abs(preClose * 0.1 + preClose - close) < DIFF_VAR
            else:
                return abs(preClose - preClose * 0.1 - close) < DIFF_VAR
        if code.startswith("sh.68") or code.startswith("sz.30"):
            if isUp:
                return abs(preClose * 0.2 + preClose - close) < DIFF_VAR
            else:
                return abs(preClose - preClose * 0.2 - close) < DIFF_VAR
        return False

    @staticmethod
    def mkdir(dir_path):
        os.makedirs(dir_path, exist_ok=True)

    @staticmethod
    def getAllFile(dir_path):
        files = []
        try:
            for file in os.listdir(dir_path):
                file_path = os.path.join(dir_path, file)
                if os.path.isfile(file_path):
                    files.append(file_path)
        except Exception as e:
            print(e)
        return files

    @staticmethod
    def getJsonData(json, path, index=0):
        assert path is not None
        assert path.startswith("$") is not True
        if index < 0:
            return jsonpath(json, '$.' + path)
        else:
            val = jsonpath(json, '$.' + path)
            try:
                if val is False:
                    return None
                else:
                    return jsonpath(json, '$.' + path)[index]
            except Exception:
                return None

    @staticmethod
    def readFile(filename):
        assert filename is not None
        with open(filename, "r", encoding='utf-8') as f:
            data = f.read()  # 读取文本
            return data

    @staticmethod
    def toJson(content):
        if content is None:
            return None
        return json.loads(content)

    @staticmethod
    def getAllFileByDay(dir_path, startDay, endDay):
        dirPrefix = 'data/trading'
        files = Objects.getAllFile(dir_path=dirPrefix)
        dayFunc = lambda x: dirPrefix + "/" + startDay + ".csv" <= x and x <= dirPrefix + "/" + endDay + ".csv"
        tradingFiles = [file for file in list(filter(dayFunc, files))]
        return tradingFiles

    @staticmethod
    def getDay(diff=0):
        day = datetime.date.today() + datetime.timedelta(days=diff)
        return day.strftime(DAY_FORMAT)

    @staticmethod
    def getDiffDay(dayStr, diff):
        day = Objects.parseDay(dayStr) + datetime.timedelta(days=diff)
        return day.strftime(DAY_FORMAT)

    @staticmethod
    def getCurrDay():
        return time.strftime("%Y-%m-%d")

    @staticmethod
    def to_db_date(trading_date):
        return trading_date.replace("-", "")

    @staticmethod
    def zipFile(dirPath, toFile='zip.zip'):
        files = Objects.getAllFile(dirPath)

        # 创建一个新的ZIP文件
        with zipfile.ZipFile(toFile, 'w', zipfile.ZIP_LZMA) as zip_ref:
            for file in files:
                zip_ref.write(file)

        return toFile

    @staticmethod
    def parseDay(dateStr):
        return datetime.datetime.strptime(dateStr, DAY_FORMAT)

    @staticmethod
    def getOneOfWeek(date):
        return date.strftime('%w')

    @staticmethod
    def isEmpty(obj):
        if obj is None:
            return True
        return len(obj) == 0

    @staticmethod
    def to_excel(file, data1, data2):
        with pd.ExcelWriter(file) as writer:
            data1.to_excel(writer, sheet_name='热点题材', index=False, freeze_panes=(1, 0), header=True)
            data2.to_excel(writer, sheet_name='涨停复盘', index=False, freeze_panes=(1, 0), header=True)
            # 获取 openpyxl 的工作簿和工作表对象
            # worksheet = writer.sheets["热点题材"]

            # 在 B2 单元格添加注释
            # worksheet['B2'].comment = Comment("This is a note for Bob's age.", "")


if __name__ == '__main__':
    print(Objects.getDay(-11))
    print(Objects.getJsonData({"a": ["b1", "b2"]}, "a.*", index=-1))
    print(Objects.getDiffDay('2025-01-01', -10))
    # print(Objects.zipFile('data/trading', 'data/all_trading_data.zip'))
